#!/bin/sh
#
# Tells Aux what the call agent is doing while it gets going, so the notebook's status line can say so
# instead of nothing. Writes $AUX_HOME/status.json (local only), which Aux watches.
#
#   aux-status <phase> ["<detail>"] [--call <tuple-call-id>]
#
# Phases, in order: starting, finding_call, loading_wiki, connecting, catching_up, listening,
# then wrapping_up and done at the end of the call; error when something stops the agent.
# The detail is one short line for the operator ("Reading profiles: Ben, Joel").

set -eu
# Aux's data folder: the app sets AUX_HOME for every process it starts; by hand, production's.
# Aux's data folder: AUX_HOME when set, else the folder of the Tuple this script ships inside (resolved
# through the bin symlink: …/TupleStaging.app/Contents/Helpers/Tuple Aux.app/…), else production's. The
# agent's shell doesn't always carry AUX_HOME (a status went to production's folder from TupleDev, 2026-11-05).
if [ -z "${AUX_HOME:-}" ]; then
    case "$(cd "$(dirname "$0")" && pwd -P)" in
        */TupleStaging.app/*) AUX_HOME="$HOME/.tuplestaging/aux" ;;
        */TupleDev.app/*)     AUX_HOME="$HOME/.tupledev/aux" ;;
        *)                    AUX_HOME="$HOME/.tuple/aux" ;;
    esac
fi

PHASES="starting finding_call loading_wiki connecting catching_up listening wrapping_up done error"
PHASE="${1:-}"
case " $PHASES " in
    *" $PHASE "*) ;;
    *) echo "usage: aux-status <$(echo $PHASES | tr ' ' '|')> [detail] [--call id]" >&2; exit 2 ;;
esac
shift
DETAIL=""
CALL=""
while [ $# -gt 0 ]; do
    case "$1" in
        --call) CALL="${2:-}"; shift 2 ;;
        *) DETAIL="$1"; shift ;;
    esac
done

esc() { printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g' | tr -d '\n\r\t'; }

DIR="$AUX_HOME"
mkdir -p "$DIR"

# An ended call doesn't speak over the one that started after it: when you switch calls, the first call's agent
# finishes its wrap-up while the next one is already listening, and its done would read as the call being over.
case "$PHASE" in wrapping_up|done|error)
    if [ -n "$CALL" ] && [ -f "$DIR/status.json" ]; then
        cur_call=$(sed -n 's/.*"call":"\([^"]*\)".*/\1/p' "$DIR/status.json")
        cur_phase=$(sed -n 's/.*"phase":"\([^"]*\)".*/\1/p' "$DIR/status.json")
        if [ -n "$cur_call" ] && [ "$cur_call" != "$CALL" ]; then
            case "$cur_phase" in done|error) ;; *) exit 0 ;; esac
        fi
    fi ;;
esac

printf '{"phase":"%s","detail":"%s","call":"%s","at":%s}\n' \
    "$PHASE" "$(esc "$DETAIL")" "$(esc "$CALL")" "$(date +%s)" > "$DIR/status.json.tmp"
mv "$DIR/status.json.tmp" "$DIR/status.json"
